<template>
  <div 
    v-if="isVisible"
    class="translate-container"
    :style="buttonStyle"
  >
    <div class="translate-panel">
      <div 
        class="translate-button"
        @click="handleTranslate"
      >
        <div v-if="!isTranslating" class="translate-icon">
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M12.87 15.07l-2.54-2.51.03-.03A17.52 17.52 0 0014.07 6H17V4h-7V2H8v2H1v2h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
          </svg>
        </div>
        <div v-else class="loading-spinner">
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M12,4V2A10,10 0 0,0 2,12H4A8,8 0 0,1 12,4Z"/>
          </svg>
        </div>
      </div>
      <select v-model="targetLang" class="lang-select">
        <option v-for="lang in supportedLanguages" :key="lang.code" :value="lang.code">
          {{ lang.name }}
        </option>
      </select>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted } from 'vue';
import { translateText } from '../utils/erpapi';

declare function setEditorContent2(text: string): Promise<boolean>;

export default defineComponent({
  name: 'TranslateButton',
  setup() {
    const isVisible = ref(false);
    const isTranslating = ref(false);
    const targetLang = ref('en');
    const buttonStyle = ref({
      top: '0px',
      left: '0px'
    });

    const supportedLanguages = [
      { code: 'en', name: '英语' },
      { code: 'zh', name: '中文' },
      { code: 'es', name: '西班牙语' },
      { code: 'fr', name: '法语' },
      { code: 'de', name: '德语' },
      { code: 'ja', name: '日语' },
      { code: 'ko', name: '韩语' },
      { code: 'ru', name: '俄语' },
      { code: 'pt', name: '葡萄牙语' },
      { code: 'it', name: '意大利语' },
      { code: 'nl', name: '荷兰语' },
      { code: 'ar', name: '阿拉伯语' },
      { code: 'hi', name: '印地语' },
      { code: 'tr', name: '土耳其语' },
      { code: 'vi', name: '越南语' },
      { code: 'th', name: '泰语' },
      { code: 'id', name: '印尼语' },
      { code: 'pl', name: '波兰语' },
      { code: 'sv', name: '瑞典语' },
      { code: 'he', name: '希伯来语' },
    ];

    const handleSelection = () => {
      const selection = window.getSelection();
      if (!selection || selection.isCollapsed) {
        isVisible.value = false;
        return;
      }

      const selectedText = selection.toString().trim();
      if (!selectedText) {
        isVisible.value = false;
        return;
      }

      const range = selection.getRangeAt(0);
      const rect = range.getBoundingClientRect();
      
      buttonStyle.value = {
        top: `${rect.top + window.scrollY - 30}px`,
        left: `${rect.right + window.scrollX}px`
      };
      
      isVisible.value = true;
    };

    const handleTranslate = async () => {
      const selection = window.getSelection();
      if (!selection) return;
      
      const selectedText = selection.toString().trim();
      if (!selectedText) return;
      
      isTranslating.value = true;
      
      try {
        const translatedText = await translateText(selectedText, targetLang.value);
        if (translatedText) {
          const success = await setEditorContent2(translatedText);
          if (!success) {
            throw new Error('插入翻译内容失败');
          }
        } else {
          throw new Error('翻译失败');
        }
      } catch (error) {
        console.error('翻译错误:', error);
      } finally {
        isTranslating.value = false;
        isVisible.value = false;
      }
    };

    // 监听选择事件
    if (typeof window !== 'undefined') {
      window.addEventListener('mouseup', handleSelection);
      window.addEventListener('keyup', handleSelection);
    }

    // 组件卸载时清理事件监听
    onUnmounted(() => {
      if (typeof window !== 'undefined') {
        window.removeEventListener('mouseup', handleSelection);
        window.removeEventListener('keyup', handleSelection);
      }
    });

    return {
      isVisible,
      isTranslating,
      buttonStyle,
      handleTranslate,
      targetLang,
      supportedLanguages
    };
  }
});
</script>

<style scoped>
.translate-container {
  position: fixed;
  z-index: 1000;
}

.translate-panel {
  display: flex;
  background-color: #00a884;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.translate-button {
  color: white;
  width: 32px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.translate-button:hover {
  background-color: #008f72;
}

.lang-select {
  height: 28px;
  border: none;
  border-left: 1px solid rgba(255, 255, 255, 0.3);
  background-color: #00a884;
  color: white;
  padding: 0 8px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
  min-width: 80px;
  appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3e%3cpath d='M7 10l5 5 5-5z'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 4px center;
  background-size: 16px;
  padding-right: 24px;
}

.lang-select:focus {
  outline: none;
  background-color: #008f72;
}

.lang-select option {
  background-color: white;
  color: #333;
}

.translate-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style> 